package org.hwadee.webSocket;

import org.hwadee.entity.User;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/webSocket/{userId}")
public class WebSocket {
    private Session session;
    private int userId;
    public static Map<Integer, WebSocket> clients = new ConcurrentHashMap<Integer, WebSocket>();

    @OnOpen
    public void onOpen(@PathParam("userId") int userId, Session session) throws IOException {
        this.userId = userId;
        this.session = session;
        clients.put(userId,this);
        System.out.println("连接成功");
    }

    @OnClose
    public void onClose() throws IOException {
        clients.remove(userId);
        System.out.println("关闭用户连接");
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        if(message.equals("HeartBeat")){
            return;
        }
        String[] infos = message.split("——");
        sendMessage(Integer.parseInt(infos[0]),infos[1],session);
    }

    public void sendMessage(int receiverId, String message, Session session) {
        for (WebSocket item : clients.values()) {
            if (item.userId==receiverId){
                item.session.getAsyncRemote().sendText(message);
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }
}